## 以下两个函数仅限于yolo标签
## check_yolo_labels函数会遍历指定文件夹中的所有 .txt 文件，提取每一行的类别编号，并统计每个类别的出现次数。
## replace_label函数可以将 folder_path 目录中的所有标签文件中某个类别编号更改为另一个类别编号
import os
from collections import Counter

def check_yolo_labels(folder_path):
    label_counter = Counter()
    
    for filename in os.listdir(folder_path):
        if filename.endswith(".txt"):  # 只处理 .txt 文件
            file_path = os.path.join(folder_path, filename)
            with open(file_path, "r") as f:
                for line in f:
                    parts = line.strip().split()
                    if parts:  # 确保行不为空
                        label = parts[0]  # 读取类别编号
                        label_counter[label] += 1
    
    return label_counter

def replace_label(folder_path, old_label, new_label):
    for filename in os.listdir(folder_path):
        if filename.endswith(".txt"):  # 只处理 .txt 文件
            file_path = os.path.join(folder_path, filename)
            lines = []
            with open(file_path, "r") as f:
                for line in f:
                    parts = line.strip().split()
                    if parts and parts[0] == old_label:
                        parts[0] = new_label  # 替换类别编号
                    lines.append(" ".join(parts))
            with open(file_path, "w") as f:
                f.write("\n".join(lines) + "\n")
                
# 示例用法
folder_path = "/home/shuai/detection_develop/RTDETR-20250111/RTDETR-main/real_USV/labels/test"  # 修改为你的标签文件夹路径
label_counts = check_yolo_labels(folder_path)
replace_label(folder_path,'0','1')
label_counts = check_yolo_labels(folder_path)
print(label_counts)